<template>
 <div class="container">
   <div class="com-chart" ref="chart_ref" style="width: 600px; height: 580px"></div>
 </div>
</template>

<script>
export default {
  name: 'airQuality',
  components: {},
  props: ['search'],
  data () {
    return {
      chartInstance: null,
      allData: [],
      setArr: []
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {
    this.initChart()
    this.getData()
    window.addEventListener('resize', this.screenAdapter)
  },
  destroyed () {
    window.removeEventListener('resize', this.screenAdapter)
  },
  methods: {
    getData () {
      this.setArr = []
      this.allData = []
      this.$axios.get(`http://api.tianapi.com/aqi/index?key=acc54cc8991613d1ef9f79b5b536b8f9&area=${this.search}`).then(res => {
        console.log('空气质量res', res)
        this.setArr = res.data.newslist[0]
        for (var i in res.data.newslist[0]) {
          const obj = {
            name: '',
            value: ''
          }
          obj.name = i
          obj.value = res.data.newslist[0][i]
          this.allData.push(obj)
        }
        console.log('空气质量', this.allData)
        this.updateChart()
      }).catch(err => {
        console.log(err)
        this.$message('暂无该省空气质量数据')
      })
    },
    setData () {
      this.$axios.post('http://127.0.0.1:7001/airQuality/input', {
        data: this.setArr
      }).then(res => {
        console.log('空气数据录入成功', res)
        this.$message({
          message: '空气数据录入成功',
          type: 'success',
          center: true
        })
      }).catch(err => {
        console.log('空气数据录入失败', err)
        this.$message('空气数据录入失败')
      })
    },
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.chart_ref, 'chalk')
      const initOption = {
        title: {
          text: '▍空气质量指数',
          top: 60,
          left: 30
        },
        grid: {
          top: '20%',
          right: '5%',
          bottom: '5%',
          left: '5%',
          containLabel: true
        },
        tooltip: {
          show: true
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              type: 'solid',
              color: 'blue',
              width: '2'
            }
          },
          axisLabel: {
            textStyle: {
              color: 'blue'
            }
          }
        },
        series: [
          {
            type: 'bar'
          }
        ]
      }
      this.chartInstance.setOption(initOption)
      this.screenAdapter()
    },
    updateChart () {
      const colorArr = [
        ['#FF0000', '#4FF778'],
        ['#FF0000', '#97F709'],
        ['#D5912B', '#79A25E']
      ]
      const nameArr = []
      this.allData.forEach(item => {
        // console.log('item', (item.value / 2).toString())
        if ((item.value / 2).toString() !== 'NaN') {
          // console.log('item.name', item.name)
          nameArr.push(item.name)
        }
      })
      const valueArr = []
      this.allData.forEach(item => {
        if ((item.value / 2).toString() !== 'NaN') {
          // console.log('item.value', item.value)
          valueArr.push(item.value)
        }
      })
      // console.log('nameArr', nameArr)
      // console.log('valueArr', valueArr)
      const dataOption = {
        xAxis: {
          data: nameArr
        },
        series: [
          {
            data: valueArr,
            itemStyle: {
              color: arg => {
                let targetColorArr = null
                if (arg.value > 300) {
                  targetColorArr = colorArr[0]
                } else if (arg.value > 200) {
                  targetColorArr = colorArr[1]
                } else {
                  targetColorArr = colorArr[2]
                }
                return new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: targetColorArr[0]
                  },
                  {
                    offset: 1,
                    color: targetColorArr[1]
                  }
                ])
              }
            }
          }
        ]
      }
      this.chartInstance.setOption(dataOption)
    },
    screenAdapter () {
      const titleFontSize = this.$refs.chart_ref.offsetWidth / 100 * 3.6
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        series: [
          {
            barWidth: titleFontSize,
            itemStyle: {
              barBorderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0] // （顺时针左上，右上，右下，左下）
            }
          }
        ]
      }
      this.chartInstance.setOption(adapterOption)
      this.chartInstance.resize()
    }
  }
}
</script>

<style scoped lang="less">

</style>
